/**
 * 
 */
package com.dhcc.android.base.utils;

import android.app.Activity;
import android.view.Gravity;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 自定义Toast，控制其产生与消失
 * @author pengling
 * @date 2015-7-13
 */
public class MyToastUtil {
	private Toast toast;
	private Field field;
	private Object obj;
	private Method showMethod, hideMethod;
	
	private Activity activity;
	
	public MyToastUtil(Activity activity,String text) {
		this.activity = activity;
		reflectionTN(text);
	}

	private void reflectionTN(String text) {
		// 创建Toast对象
		toast = Toast.makeText(activity, text, 1);
		toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL,
				0, 0);
		try {
			field = toast.getClass().getDeclaredField("mTN");
			field.setAccessible(true);
			obj = field.get(toast);
			showMethod = obj.getClass().getDeclaredMethod("show", new Class[0]);
			hideMethod = obj.getClass().getDeclaredMethod("hide", new Class[0]);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void stopToast() {
		try {
			hideMethod.invoke(obj, new Object[]{});// 调用TN对象的hide()方法，关闭toast
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void startToast() {
		try {
			showMethod.invoke(obj, new Object[]{});// 调用TN对象的show()方法，显示toast
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
}
